#include "CLSerializer.h"
#include <iostream>

using namespace std;

// 序列化
bool CLSerializer::Serialize(const char *pFilePath, std::vector<IGoodsPlugin *> &v)
{
    // 保存的文件
    FILE *fp = fopen(pFilePath, "w+");
    if (fp == NULL)
        return false;
    cout << "序列化控制器执行了" << v.size() <<"个类的序列化任务"<< endl;
    for (int i = 0; i < v.size(); i++)
    {
        cout << "i=" << i ;
        v[i]->PrintInfo();
        int type;
        v[i]->GetType(type);
        fwrite(&type, sizeof(int), 1, fp);
        v[i]->Serialize(fp);
    }
    fclose(fp);
    return true;
}

// 反序列化
bool CLSerializer::Deserialize(const char *pFilePath, std::vector<IGoodsPlugin *> &v)
{
    FILE *fp = fopen(pFilePath, "r+");
    if (fp == NULL)
        return false;
    for (;;)
    {
        int nType = -1;
        int r = fread(&nType, sizeof(int), 1, fp);

        int type;
        for (int i = 0; i < m_vSerialized.size(); i++)
        {
            m_vSerialized[i]->GetType(type);
            if (type == nType)
            {
                IGoodsPlugin *p = m_vSerialized[i]->Deserialize(fp);
                if (p != NULL)
                    v.push_back(p);
            }
        }
        if (r == 0)
            break;
    }
    fclose(fp);
    return true;
}

// 插件更新
void CLSerializer::Register(IGoodsPlugin *pSerialized)
{
    m_vSerialized.push_back(pSerialized);
}
